package com.dbpms.pj.common;


import org.apache.commons.collections.map.LinkedMap;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * @Author: Song Yu
 * @Date: 2020/10/26 15:35
 */

@Configuration //配置对象注解，特殊的bean
public class SpringShiroConfig {

    @Bean//此注解标注的方法其返回值会交给spring管理
    public SecurityManager securityManager(Realm realm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm);
        return securityManager;
    }

    @Bean
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){
        LifecycleBeanPostProcessor lifecycleBeanPostProcessor = new LifecycleBeanPostProcessor();
        return lifecycleBeanPostProcessor;
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }


    @Bean//此对象需要配置一些访问规则（匿名访问的资源，认证的访问的资源）
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setLoginUrl("/doLoginUI");
        factoryBean.setSecurityManager(securityManager);//securityManager负责去检测这个请求是否已经认证
        Map<String,String> filterMap = new LinkedMap();
        //静态资源允许匿名访问:"anon"
        filterMap.put("/bower_components/**","anon");
        filterMap.put("/build/**","anon");
        filterMap.put("/dist/**","anon");
        filterMap.put("/plugins/**","anon");
        filterMap.put("/user/doLogin","anon");
        //除了匿名访问的资源,其它都要认证("authc")后访问
        filterMap.put("/**","authc");
        factoryBean.setFilterChainDefinitionMap(filterMap);//过滤链的定义
        return factoryBean;
    }
}
